package com.dkm.biz.gl.util;

import java.text.ParseException;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.ProxyUtil;
import com.dkm.base.core.util.string.StringUtils;
import com.dkm.biz.gl.persistence.entity.ValidatePo;
import com.dkm.biz.gl.repository.ValidateRepository;

/**
 * 验证工具类
 * 
 * @author Administrator
 * 
 */
public class ValidateUtil {

	/**
	 * @param key
	 *            验证业务键
	 * @param value
	 *            验证值 return “”验证通过 ， 否则验证不通过
	 * @throws ParseException
	 */
	public static String validate(String key, Object o) throws ParseException {
		String msg = "";
		if (StringUtils.isEmpty(key) || o == null || "".equals(o.toString())) {
			return msg;
		}
		// ValidateInfo
		// validateInfo=SearchInfoHelper.getValidateInfo(itableName+keys);
		ValidateRepository validateRepository = SpringHelper
				.getBean(ValidateRepository.class);
		ValidatePo po = validateRepository.getByKey(key);
		if (po == null) {
			return msg;
		}
		/**
		 * 判断是否必填
		 */
		if (po.getRequire() == '1' && StringUtils.isEmpty(o.toString())) {
			return po.getRequireMsg();
		}
		/**
		 * 判断字符长度 长度范围 [l0,l1] 最大长度 length
		 */
		String length = po.getLength();
		if (!StringUtils.isEmpty(length)) {
			if (length.indexOf(",") > 0) {
				length = length.substring(1, length.length() - 1);
				String[] l = length.split(",");
				if (Integer.valueOf(l[0]) > po.getLength().length()
						|| Integer.valueOf(l[1]) < po.getLength().length()) {
					return po.getLengthMsg();
				}
			} else if (Integer.valueOf(length) < po.getLength().length()) {
				return po.getLengthMsg();
			}
		}
		/**
		 * 判断是否满足正则表达式
		 */
		if (StringUtils.isNotEmpty(po.getRegx())
				&& !o.toString().matches(po.getRegx())) {
			return po.getRequireMsg();
		}
		/**
		 * 判断是否等于
		 */
		if (StringUtils.isNotEmpty(po.getEqual())
				&& po.getEqual().equals(o.toString())) {
			return po.getEqualMsg();
		}
		if(StringUtils.isNotEmpty(po.getAjax())){
			String result=ProxyUtil.httpRequest(po.getAjax(), "GET", "p1="+o.toString());
			if(result==null||result.indexOf("200")==-1){
				return po.getAjaxMsg();
			}
		}
		return msg;
	}

}
